package com.lagou.rpc.consumer.zkClient;

import org.I0Itec.zkclient.ZkClient;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * @Description
 * @Classname ZkClientUtil
 * @Date 2021/5/9 16:46
 * @Author ch'ien
 */
@Component
public class ZkClientUtil {

    private static final String PATH = "/my_server";
    private static long FIVE_TIME = 5*1000L;
    @Scheduled(cron = "0/5 * * * * ?")
    public void heartBeat(){
        ZkClient zkClient = new ZkClient("192.168.172.130:2181");
        System.out.println("查找可用服务上报。。。");
        List<String> serverList = zkClient.getChildren(PATH);
        for (String s : serverList) {
            Map<String,Object> o = zkClient.readData(PATH+"/"+s);
            System.out.println("--------------------------------------------------");
            System.out.println("服务："+s);
            if (o != null) {
                Object sysTime = o.get("sysTime");
                Object reqTime = o.get("reqTime");
                System.out.println("系统时间："+sysTime);
                System.out.println("请求耗时："+reqTime);
                if (sysTime != null){
                    Long l = (Long) sysTime;
                    if(System.currentTimeMillis()-l>FIVE_TIME){
                        o.put("reqTime" ,null);
                        zkClient.writeData(PATH+"/"+s,o);
                    }
                }
            }
            System.out.println("--------------------------------------------------");

        }
        System.out.println("查找可用服务上报结束。。。");
    }
}
